package com.zhangyanqiang.traceId.filter;

import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhangyanqiang
 * @date 2020/7/30
 **/
@Activate(group = "consumer",order = -1)
public class DubboConsumerTraceFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(WebTraceIdFilter.class);
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        try{

            String logTraceId = TraceIdUtil.getLogTraceId();
            if (StringUtils.isEmpty(logTraceId)){
                TraceIdUtil.addTraceId();
            }
            RpcContext.getContext().setAttachment(TraceIdUtil.logTraceId,TraceIdUtil.getLogTraceId());
        }catch (Exception e){
            logger.error("failed to add dubbo traceId:{}",e);
        }

        return invoker.invoke(invocation);
    }
}
